package com.gitee.swsk33.websockethandlerdemo.config;

import com.gitee.swsk33.websockethandlerdemo.handler.websocket.BinaryWebSocketHandler;
import com.gitee.swsk33.websockethandlerdemo.handler.websocket.ObjectWebSocketHandler;
import com.gitee.swsk33.websockethandlerdemo.handler.websocket.PathWebSocketHandler;
import com.gitee.swsk33.websockethandlerdemo.handler.websocket.TextWebSocketHandler;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * 配置我们的WebSocket处理器
 */
@Configuration
@EnableWebSocket
public class WebSocketHandlerConfig implements WebSocketConfigurer {

	@Autowired
	private BeanFactory beanFactory;

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		// 获取我们的WebSocket处理器Bean对象
		TextWebSocketHandler textHandler = beanFactory.getBean(TextWebSocketHandler.class);
		ObjectWebSocketHandler objectHandler = beanFactory.getBean(ObjectWebSocketHandler.class);
		BinaryWebSocketHandler binaryHandler = beanFactory.getBean(BinaryWebSocketHandler.class);
		PathWebSocketHandler pathHandler = beanFactory.getBean(PathWebSocketHandler.class);
		// 注册WebSocket处理器，并使其和路径对应
		registry.addHandler(textHandler, "/ws/text")
				.addHandler(objectHandler, "/ws/object")
				.addHandler(binaryHandler, "/ws/binary")
				.addHandler(pathHandler, "/ws/path/{userId}")
				// 允许跨域请求
				.setAllowedOriginPatterns("*");
	}

}